﻿using Microsoft.TeamFoundation.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CMS6Tools.Common.TFS
{
    internal abstract class FederatedCookieHelper
    {
        private static readonly string _federatedCookieName = "FedAuth";
        internal static void EnsureFederatedIdentityCookies(TfsTeamProjectCollection server, System.Net.HttpWebRequest request)
        {
            if (request == null)
            {
                throw new System.ArgumentNullException("request");
            }
            if (request.CookieContainer == null)
            {
                request.CookieContainer = new System.Net.CookieContainer();
            }
            System.Collections.Generic.IEnumerable<System.Net.Cookie> federatedIdentityCookies = FederatedCookieHelper.GetFederatedIdentityCookies(server);
            if (federatedIdentityCookies != null && federatedIdentityCookies.Any<System.Net.Cookie>())
            {
                foreach (System.Net.Cookie current in federatedIdentityCookies)
                {
                    request.CookieContainer.Add(current);
                }
            }
        }
        private static System.Collections.Generic.IEnumerable<System.Net.Cookie> GetFederatedCookies(System.Uri uri)
        {
            if (uri == null)
            {
                throw new System.ArgumentNullException("uri");
            }
            System.Collections.Generic.IEnumerable<System.Net.Cookie> result;
            try
            {
                System.Net.CookieCollection federatedCookies = FederatedAcsLogon.GetFederatedCookies(uri);
                if (federatedCookies != null && federatedCookies.Count != 0)
                {
                    System.Collections.Generic.IEnumerable<System.Net.Cookie> enumerable =
                        from c in federatedCookies.OfType<System.Net.Cookie>()
                        where c.Name.StartsWith(FederatedCookieHelper._federatedCookieName)
                        select c;
                    result = enumerable;
                    return result;
                }
            }
            catch (System.Exception)
            {
                throw;
            }
            result = null;
            return result;
        }
        private static System.Collections.Generic.IEnumerable<System.Net.Cookie> GetFederatedIdentityCookies(TfsTeamProjectCollection server)
        {
            if (server == null)
            {
                throw new System.ArgumentNullException("server");
            }
            System.Collections.Generic.IEnumerable<System.Net.Cookie> result;
            if (server.IsTfsService())
            {
                System.Collections.Generic.IEnumerable<System.Net.Cookie> enumerable = FederatedCookieHelper.GetFederatedCookies(FederatedCookieHelper.GetUriForServer(server));
                if (enumerable == null)
                {
                    System.Net.CookieCollection federatedCookies = FederatedAcsLogon.GetFederatedCookies(server.Uri);
                    if (federatedCookies != null && federatedCookies.Count > 0)
                    {
                        enumerable = federatedCookies.OfType<System.Net.Cookie>();
                    }
                }
                if (enumerable != null)
                {
                    foreach (System.Net.Cookie current in enumerable)
                    {
                        current.Path = "/";
                        if (server.Name.IndexOf(".tfspreview.com", System.StringComparison.CurrentCultureIgnoreCase) != -1)
                        {
                            current.Domain = ".tfspreview.com";
                        }
                        else
                        {
                            if (server.Name.IndexOf(".visualstudio.com", System.StringComparison.CurrentCultureIgnoreCase) != -1)
                            {
                                current.Domain = ".visualstudio.com";
                            }
                        }
                    }
                    result = enumerable;
                    return result;
                }
            }
            result = null;
            return result;
        }
        private static System.Uri GetUriForServer(TfsTeamProjectCollection server)
        {
            if (server == null)
            {
                throw new System.ArgumentNullException("server");
            }
            if (!server.IsTfsService())
            {
                throw new System.InvalidOperationException("Server must be on Team Foundation Service");
            }
            string name = server.Name;
            if (string.IsNullOrEmpty(name))
            {
                throw new System.InvalidOperationException("Server does not have a name");
            }
            System.Uri result;
            if (name.ToLowerInvariant().Contains(".tfspreview.com"))
            {
                result = new System.Uri("https://tfspreview.com");
            }
            else
            {
                if (!name.ToLowerInvariant().Contains(".visualstudio.com"))
                {
                    throw new System.InvalidOperationException("Uknown Team Foundation Service provider");
                }
                result = new System.Uri("https://tfs.visualstudio.com");
            }
            return result;
        }
    }
}
